package com.channel.temperature.collect.ui.fragment

import android.content.Intent
import android.content.res.Configuration
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.github.gzuliyujiang.wheelpicker.DatimePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.HBluetooth
import com.hjy.bluetooth.entity.BluetoothDevice
import com.hjy.bluetooth.inter.ConnectCallBack
import com.hjy.bluetooth.operator.abstra.Sender
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBackPressedListener
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseFragment
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.CRC16Utils
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.data.response.TaskBean
import com.channel.temperature.collect.databinding.FragmentTaskBinding
import com.channel.temperature.collect.ui.activity.AddTaskActivity
import com.channel.temperature.collect.ui.activity.BLEActivity
import com.channel.temperature.collect.ui.activity.DeviceListActivity
import com.channel.temperature.collect.ui.adapter.TaskAdapter
import com.channel.temperature.collect.ui.viewmodel.TaskModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.appContext
import me.hgj.mvvmhelper.ext.divider
import me.hgj.mvvmhelper.ext.getColorExt
import me.hgj.mvvmhelper.ext.grid
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import me.hgj.mvvmhelper.util.decoration.DividerOrientation
import okio.internal.commonAsUtf8ToByteArray
import java.text.SimpleDateFormat
import java.util.*

class TaskFragment : BaseFragment<TaskModel, FragmentTaskBinding>() {

    companion object {
        fun newInstance(): TaskFragment {
            val args = Bundle()
            val fragment = TaskFragment()
            fragment.arguments = args
            return fragment
        }
    }

    lateinit var dialog: WaitDialog
    private val mTaskAdapter: TaskAdapter by lazy { TaskAdapter() }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun initView(savedInstanceState: Bundle?) {
        Log.e("任务列表", "任务列表")
        mBind.customToolbar.initBack("保压取心工具数据测量") {
            val messageDialog = MessageDialog(
                "提示", "退出程序？", "确定", "取消"
            ).setButtonOrientation(LinearLayout.HORIZONTAL)
            messageDialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                lifecycleScope.launch {
                    HBluetooth.getInstance().release()
                    activity?.finish()
                }
                false
            }
            if (this.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                messageDialog.setMaxWidth(resources.displayMetrics.widthPixels / 2)
            }
            messageDialog.show()
        }
        mBind.customToolbar.setRightDrawable(R.mipmap.icon_unconnected)
        if (activity?.resources?.configuration?.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mBind.listRecyclerView.grid(2)
        } else {
            mBind.listRecyclerView.grid(1)
        }
        mBind.listRecyclerView.divider {
            orientation = DividerOrientation.GRID
            includeVisible = true
            setColor(getColorExt(com.channel.temperature.collect.R.color.common_text_hint_color))
        }.adapter = mTaskAdapter
        mTaskAdapter.setOnItemLongClickListener { adapter, view, position ->
            val messageDialog = MessageDialog(
                "提示", "编辑当前数据？", "确定", "取消"
            ).setButtonOrientation(LinearLayout.HORIZONTAL)
            messageDialog.maxWidth =
                if (appContext.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE)
                    appContext.resources.displayMetrics.widthPixels / 2 else appContext.resources.displayMetrics.widthPixels
            messageDialog.okButtonClickListener = OnDialogButtonClickListener { dialog, v ->
                lifecycleScope.launch {
                    var currentData = mViewModel.tasklistData.value?.get(position)
                    currentData?.let {
                        var bund = Bundle()
                        bund.putString("time", it.taskTime)
                        bund.putInt("interval", it.delayTime)
                        bund.putInt("position", position)
                        toStartActivity(requireActivity(), AddTaskActivity::class.java, 2, bund)
                    }

                }
                false
            }
            messageDialog.show()
            false
        }
        mViewModel.resetClickType()
        setConnectStatusRightImage()
        mViewModel.sendTaskOrAutoTask.value = -1
        LiveDataEvent.notifyReReadSystemInfo.value == false
        LiveDataEvent.checkedWorkMode.value = 1
        if (savedInstanceState != null) {
            LiveDataEvent.checkedWorkMode.value = savedInstanceState.getInt("checkedWorkMode", 1)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        LiveDataEvent.checkedWorkMode.value?.let {
            outState.putInt("checkedWorkMode", it)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("onActivityResult", "onActivityResult " + requestCode + "   " + resultCode)
        if (requestCode == 2) {
            var delay = data?.getIntExtra("delay", 0)
            var index = data?.getIntExtra("index", 0)
            var time = data?.getStringExtra("time")
            Log.e("onActivityResult", "得到的值 ： " + delay + "   " + index + " " + time)
            var mTaskBean = delay?.let {
                time?.let { it1 ->
                    TaskBean(
                        taskTime = it1, delayTime = it, isSelected = false, isRemote = false
                    )
                }
            }
            var listData = mViewModel.tasklistData.value
            index?.let { mTaskBean?.let { it1 -> listData?.set(it, it1) } }
            mViewModel.tasklistData.value = listData
        }

    }

    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mBind.customToolbar.getRightId(),
            mBind.sendTaskCMD,
            mBind.chooseStartTime,
            mBind.chooseEndTime,
            mBind.queryTasks,
            mBind.disconnect,
            mBind.sendAutoTask,
            mBind.offlineMode,
            mBind.pressMode
        ) {

            when (it) {
                mBind.customToolbar.getRightId() -> {
                    if (HBluetooth.getInstance().isConnected) {
                        Log.e("右上角", " 已经连接")
                        val messageDialog = MessageDialog(
                            "提示",
                            "目前已连接${LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name},是否断开连接其它设备？",
                            "确定",
                            "取消"
                        ).setButtonOrientation(LinearLayout.HORIZONTAL)
                        if (this.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                            messageDialog.setMaxWidth(resources.displayMetrics.widthPixels / 2)
                        }
                        messageDialog.okButtonClickListener =
                            OnDialogButtonClickListener { dialog, v ->
                                HBluetooth.getInstance().release()
                                var bund = Bundle()
                                bund.putInt(ValueKey.DeviceType, 3)
                                toStartActivity(DeviceListActivity::class.java, bund)
                                false
                            }
                        messageDialog.show()


                    } else {
                        Log.e("右上角", " 没有连接")
                        var bund = Bundle()
                        bund.putInt(ValueKey.DeviceType, 3)
                        toStartActivity(DeviceListActivity::class.java, bund)
                    }

                }

                mBind.offlineMode -> {
                    LiveDataEvent.checkedWorkMode.value = 1
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
//                    setNewMode()
                    if (HBluetooth.getInstance().isConnected) {
                        mViewModel.needFoldData = false
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 9
                            var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.pressMode -> {
                    LiveDataEvent.checkedWorkMode.value = 2
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
//                    setNewMode()
                    if (HBluetooth.getInstance().isConnected) {
                        mViewModel.needFoldData = false
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 9
                            var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

//                mBind.systemSetting -> {
//                    toStartActivity(SystemSettingActivity::class.java)
//                }

                mBind.disconnect -> {
                    HBluetooth.getInstance().release()
                }

//                mBind.addTask -> {
//                    if (mTaskAdapter.data.size >= 8) {
//                        ToastUtils.show("无法添加，最多存在8条任务，请先长按列表删除其它任务再添加")
//                    } else {
//                        toStartActivity(AddTaskActivity::class.java)
//                    }
//
//                }

                mBind.queryTasks -> {

                    if (HBluetooth.getInstance().isConnected) {
                        mViewModel.needFoldData = false
                        HBluetooth.getInstance().sender()?.let { it1 ->
                            mViewModel.clickType = 9
                            var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                            mViewModel.sendCommonCMD(
                                it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }

                }

                mBind.sendAutoTask -> {

                    lifecycleScope.launch {
                        if (HBluetooth.getInstance().isConnected) {
                            HBluetooth.getInstance().sender()?.let { it1 ->
                                var date = Date()
                                val format = SimpleDateFormat("yyMMddHHmmss")
                                val str = format.format(date)
                                Log.e("校时", "校时str  " + str)
                                var year = MyUtil.numberToHexOne(str.substring(0, 2).toInt())
                                var month = MyUtil.numberToHexOne(str.substring(2, 4).toInt())
                                var day = MyUtil.numberToHexOne(str.substring(4, 6).toInt())
                                var hour = MyUtil.numberToHexOne(str.substring(6, 8).toInt())
                                var minute = MyUtil.numberToHexOne(str.substring(8, 10).toInt())
                                var second = MyUtil.numberToHexOne(str.substring(10, 12).toInt())
                                var time = "" + year + month + day + hour + minute + second
                                Log.e("校时", "校时1111111    " + time)
                                mViewModel.checkTimeClick = 2
                                mViewModel.clickType = 5
                                var cmd = "FF55AA000A" + getAddress() + "4202$time"
                                mViewModel.sendCommonCMD(
                                    it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                )
                            }
                        } else {
                            ToastUtils.show("请先连接设备后再操作")
                        }


                    }


                }

                mBind.sendTaskCMD -> {

                    lifecycleScope.launch {
                        if (HBluetooth.getInstance().isConnected) {
                            HBluetooth.getInstance().sender()?.let { it1 ->
                                var date = Date()
                                val format = SimpleDateFormat("yyMMddHHmmss")
                                val str = format.format(date)
                                Log.e("校时", "校时str  " + str)
                                var year = MyUtil.numberToHexOne(str.substring(0, 2).toInt())
                                var month = MyUtil.numberToHexOne(str.substring(2, 4).toInt())
                                var day = MyUtil.numberToHexOne(str.substring(4, 6).toInt())
                                var hour = MyUtil.numberToHexOne(str.substring(6, 8).toInt())
                                var minute = MyUtil.numberToHexOne(str.substring(8, 10).toInt())
                                var second = MyUtil.numberToHexOne(str.substring(10, 12).toInt())
                                var time = "" + year + month + day + hour + minute + second
                                Log.e("校时", "校时1111111    " + time)
                                mViewModel.checkTimeClick = 1
                                mViewModel.clickType = 5
                                var cmd = "FF55AA000A" + getAddress() + "4202$time"
                                mViewModel.sendCommonCMD(
                                    it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                )
                            }
                        } else {
                            ToastUtils.show("请先连接设备后再操作")
                        }
                    }

                }


                mBind.chooseStartTime -> {
                    var picker = DatimePicker(requireActivity())
                    var wheelLayout = picker.wheelLayout
                    picker.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        var text = "$year-$month-$day $hour:$minute:$second"
                        mBind.chooseStartTime.text = MyUtil.DateToStr(MyUtil.StrToDate(text))
                        var timeByteArray: ByteArray = byteArrayOf(
                            year.toString().substring(2, 4).toInt().toByte(),
                            month.toByte(),
                            day.toByte(),
                            hour.toByte(),
                            minute.toByte(),
                            second.toByte()
                        )
                        Log.e("选择的时间", "选择的开始时间 ：" + MyUtil.bytes2Hex(timeByteArray))
                        mmkv.putString(
                            ValueKey.COLLECTION_START_TIME, MyUtil.DateToStr(MyUtil.StrToDate(text))
                        )
                        mmkv.putString(
                            ValueKey.COLLECTION_START_TIME_CMD, MyUtil.bytes2Hex(timeByteArray)
                        )
                    }


                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    wheelLayout.setRange(DatimeEntity.now(), DatimeEntity.yearOnFuture(10))
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                    picker.show()

                }

                mBind.chooseEndTime -> {
                    var picker = DatimePicker(requireActivity())
                    var wheelLayout = picker.wheelLayout
                    picker.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        var text = "$year-$month-$day $hour:$minute:$second"
                        mBind.chooseEndTime.text = MyUtil.DateToStr(MyUtil.StrToDate(text))
                        var timeByteArray: ByteArray = byteArrayOf(
                            year.toString().substring(2, 4).toInt().toByte(),
                            month.toByte(),
                            day.toByte(),
                            hour.toByte(),
                            minute.toByte(),
                            second.toByte()
                        )
                        Log.e("选择的时间", "选择的结束时间 ：" + MyUtil.bytes2Hex(timeByteArray))
                        mmkv.putString(
                            ValueKey.COLLECTION_END_TIME, MyUtil.DateToStr(MyUtil.StrToDate(text))
                        )
                        mmkv.putString(
                            ValueKey.COLLECTION_END_TIME_CMD, MyUtil.bytes2Hex(timeByteArray)
                        )
                    }
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    wheelLayout.setRange(DatimeEntity.now(), DatimeEntity.yearOnFuture(10))
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                    picker.show()
                }

            }
        }
    }

    public fun get40Bytes(): ByteArray {
        var originString = "                                        "//默认40个空格
        var deviceNameByteArray = ByteArray(40)
        var dataBytes = originString.commonAsUtf8ToByteArray()
        System.arraycopy(
            dataBytes, 0, deviceNameByteArray, 0, dataBytes.size
        )
        return deviceNameByteArray
    }

    public fun wakeUp() {
        mViewModel.continueSendWakeUpCMD = true
        if (HBluetooth.getInstance().isConnected) {
            lifecycleScope.launch {
                var i = 0
                flow<Int> {
                    while (mViewModel.continueSendWakeUpCMD) {
                        Log.e("唤醒", "while 唤醒  " + i)
                        i++
                        if (i == 30) {
                            mViewModel.continueSendWakeUpCMD = false
                        } else {
                            mViewModel.continueSendWakeUpCMD = true
                            emit(i)
                            delay(10)
                        }

                    }
                }.collect {
                    HBluetooth.getInstance().sender()?.let { it1 ->
                        mViewModel.clickType = 3
                        var cmd = "FF55AA0004" + getAddress() + "4001"
                        mViewModel.sendCommonCMD(
                            it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                        )
                    }
                }

            }

        } else {
            ToastUtils.show("请先连接设备后再操作")
        }
    }

    private fun getAddress(): String {
        return "FA"
    }

    private fun connectDevice(bluetoothDevice: BluetoothDevice?) {
        Log.e("connectDevice", "connectDevice    " + bluetoothDevice?.name)
        lifecycleScope.launch {
            HBluetooth.getInstance().connect(bluetoothDevice, object : ConnectCallBack {
                override fun onConnecting() {
                    Log.e(BLEActivity.TAG, "连接中...")
                    dialog.setMessageContent(LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "连接中...")
                }

                override fun onConnected(sender: Sender) {
                    Log.e(
                        BLEActivity.TAG,
                        "连接成功,isConnected:" + HBluetooth.getInstance().isConnected
                    )
                    lifecycleScope.launch {
                        mBind.customToolbar.setRightDrawable(R.mipmap.icon_connected)
                    }

                    dialog.setMessageContent("连接成功")
//                    mBind.connectStatus?.text =
//                        LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "连接成功"
                    ToastUtils.show(LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "连接成功")
                    dialog.doDismiss()
                    wakeUp()
                }

                override fun onDisConnecting() {
                    Log.e(BLEActivity.TAG, "断开连接中...")
                }

                override fun onDisConnected() {
                    Log.e(
                        BLEActivity.TAG,
                        "已断开连接,isConnected:" + HBluetooth.getInstance().isConnected
                    )

                    lifecycleScope.launch {

                        try {
                            var mBindTemp = mBind
                            if (mBindTemp != null) {
                                mBindTemp.customToolbar.setRightDrawable(R.mipmap.icon_unconnected)
                            }

                        } catch (e: NullPointerException) {
                            Log.e("捕捉到异常了", "捕捉到异常了")
                        }
                    }


                    ToastUtils.show(LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "已断开连接")
//                    if (mBind != null) {
//                        mBind.connectStatus.text =
//                            LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "已断开连接"
//                        dialog?.setMessageContent(LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + " 已断开连接")
//                        dialog?.doDismiss()
//                    }

                }

                override fun onError(errorType: Int, errorMsg: String) {
                    Log.e(BLEActivity.TAG, "错误类型：$errorType 错误原因：$errorMsg")
                    ToastUtils.show(LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "错误类型：$errorType 错误原因：$errorMsg")
//                    mBind.connectStatus.text =
//                        LiveDataEvent.connectSPPDevice.value?.bluetoothDevice?.name + "错误类型：$errorType 错误原因：$errorMsg"
                    dialog.setMessageContent("错误类型：$errorType 错误原因：$errorMsg")
                    dialog.doDismiss()
                } //低功耗蓝牙才需要BleNotifyCallBack
                //经典蓝牙可以只调两参方法connect(BluetoothDevice device, ConnectCallBack connectCallBack)
            })
        }

    }

    private fun initListener() {
        HBluetooth.getInstance().setReceiver { dataInputStream, result -> //设备发过来的数据将在这里出现
            Log.e(
                "测试返回数据",
                result.size.toString() + "收到蓝牙设备返回数据111111111111111111->" + MyUtil.bytes2Hex(
                    result
                )
            )
            mViewModel.handleBLEResult(result)
        }
    }

    /**
     * 懒加载 第一次获取视图的时候 触发
     */
    override fun lazyLoadData() {
//        activity?.let {
//            mViewModel.getRoomListData(it.applicationContext)
//        }
    }


    override fun onRequestSuccess() {
        LiveDataEvent.checkedWorkMode.observe(this, Observer {
            lifecycleScope.launch {
                if (it == 2) {
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                } else {
                    mBind.offlineMode.setBackgroundResource(R.drawable.bg_work_mode_selected)
                    mBind.pressMode.setBackgroundResource(R.drawable.bg_work_mode_unselected)
                }
            }
        })

        mViewModel.sendTaskOrAutoTask.observe(this, Observer {
            lifecycleScope.launch {
                when (it) {

                    2 -> {
                        if (mBind.chooseStartTime.text.toString().trim()
                                .isNullOrEmpty() || mBind.chooseEndTime.text.toString().trim()
                                .isNullOrEmpty()
                        ) {
                            ToastUtils.show("采集开始时间 采集结束时间不能为空")
                        } else {
                            PopupWindow().apply {
                                //入口参数配置
                                contentView =
                                    layoutInflater.inflate(R.layout.pop_add_task_desc, null)
                                width = ViewGroup.LayoutParams.MATCH_PARENT
                                height = ViewGroup.LayoutParams.MATCH_PARENT
                                isFocusable = true
                                val dw = ColorDrawable(0xb0000000.toInt())
                                setBackgroundDrawable(dw)
                                //设置按钮
                                val btnPopupWindow =
                                    contentView.findViewById<RelativeLayout>(R.id.popLayout)
                                val save = contentView.findViewById<TextView>(R.id.saveTask)
                                val deviceName = contentView.findViewById<TextView>(R.id.deviceET)
                                val taskName = contentView.findViewById<EditText>(R.id.taskNameET)
                                val taskDesc = contentView.findViewById<EditText>(R.id.taskDesET)
                                val linearLayout =
                                    contentView.findViewById<LinearLayout>(R.id.popViewLayout)
                                deviceName.setText(mViewModel.taskDeviceName)
                                taskName.setText(mViewModel.taskCurrentName)
                                taskDesc.setText(mViewModel.taskDesc)
                                save.setOnClickListener {
                                    dismiss()
                                    if (!deviceName.text.toString().trim()
                                            .isNullOrEmpty() && !taskName.text.toString().trim()
                                            .isNullOrEmpty()
                                    ) {
                                        if (HBluetooth.getInstance().isConnected) {
                                            HBluetooth.getInstance().sender()?.let { it1 ->
                                                mViewModel.clickType = 15
                                                var cmd =
                                                    "FF55AA0082" + getAddress() + "4502000010300078"

                                                var deviceBytes = get40Bytes()
                                                System.arraycopy(
                                                    deviceName.text.toString()
                                                        .commonAsUtf8ToByteArray(),
                                                    0,
                                                    deviceBytes,
                                                    0,
                                                    deviceName.text.toString()
                                                        .commonAsUtf8ToByteArray().size
                                                )
                                                var taskNameBytes = get40Bytes()
                                                System.arraycopy(
                                                    taskName.text.toString()
                                                        .commonAsUtf8ToByteArray(),
                                                    0,
                                                    taskNameBytes,
                                                    0,
                                                    taskName.text.toString()
                                                        .commonAsUtf8ToByteArray().size
                                                )
                                                var taskDescBytes = get40Bytes()
                                                if (!taskDesc.text.toString().trim()
                                                        .isNullOrEmpty()
                                                ) {
                                                    System.arraycopy(
                                                        taskDesc.text.toString()
                                                            .commonAsUtf8ToByteArray(),
                                                        0,
                                                        taskDescBytes,
                                                        0,
                                                        taskDesc.text.toString()
                                                            .commonAsUtf8ToByteArray().size
                                                    )
                                                }
                                                cmd =
                                                    cmd + MyUtil.bytes2Hex(deviceBytes) + MyUtil.bytes2Hex(
                                                        taskNameBytes
                                                    ) + MyUtil.bytes2Hex(taskDescBytes)
                                                mViewModel.sendCommonCMD(
                                                    it1,
                                                    cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                                )
                                            }
                                        } else {
                                            ToastUtils.show("请先连接设备后再操作")
                                        }
                                    } else {
                                        ToastUtils.show("设备名称 当前任务名称不能为空")
                                    }

                                }
                                btnPopupWindow.setOnClickListener {
                                    dismiss()
                                }
                                linearLayout.setOnClickListener {}
                                showAtLocation(contentView, Gravity.CENTER, 0, 0)
                            }
                        }
                    }

                    3 -> {
                        PopupWindow().apply {
                            //入口参数配置
                            contentView =
                                layoutInflater.inflate(R.layout.pop_add_auto_task_desc, null)
                            width = ViewGroup.LayoutParams.MATCH_PARENT
                            height = ViewGroup.LayoutParams.MATCH_PARENT
                            isFocusable = true
                            val dw = ColorDrawable(0xb0000000.toInt())
                            setBackgroundDrawable(dw)
                            //设置按钮
                            val btnPopupWindow =
                                contentView.findViewById<RelativeLayout>(R.id.popLayout)
                            val linearLayout =
                                contentView.findViewById<LinearLayout>(R.id.popViewLayout)
                            val save = contentView.findViewById<TextView>(R.id.saveTask)
                            val deviceName = contentView.findViewById<TextView>(R.id.deviceET)
                            val taskName = contentView.findViewById<EditText>(R.id.taskNameET)
                            val taskDesc = contentView.findViewById<EditText>(R.id.taskDesET)
                            val delayTimeET = contentView.findViewById<EditText>(R.id.jiangeET)
                            val pressureET = contentView.findViewById<EditText>(R.id.pressureET)
                            val pressureETLayout =
                                contentView.findViewById<LinearLayout>(R.id.pressLayout)
                            val pressureDivide =
                                contentView.findViewById<View>(R.id.pressLayoutDivide)
                            val initDelayET = contentView.findViewById<EditText>(R.id.initDelayET)
                            deviceName.setText(mViewModel.taskDeviceName)
                            taskName.setText(mViewModel.taskCurrentName)
                            taskDesc.setText(mViewModel.taskDesc)
                            if (LiveDataEvent.checkedWorkMode.value == 2) {
                                pressureETLayout.visibility = View.VISIBLE
                                pressureDivide.visibility = View.VISIBLE
                                delayTimeET.setText("6")
                            } else {
                                pressureETLayout.visibility = View.GONE
                                pressureDivide.visibility = View.GONE
                            }

                            save.setOnClickListener {
                                dismiss()
                                var canSave = false
                                if (LiveDataEvent.checkedWorkMode.value == 2) {
                                    if (!deviceName.text.toString().trim()
                                            .isNullOrEmpty() && !taskName.text.toString().trim()
                                            .isNullOrEmpty() && !delayTimeET.text.toString().trim()
                                            .isNullOrEmpty() && !pressureET.text.toString().trim()
                                            .isNullOrEmpty() && !initDelayET.text.toString().trim()
                                            .isNullOrEmpty()
                                    ) {
                                        mViewModel.setIntervalTime =
                                            delayTimeET.text.toString().trim().toInt()
                                        var pressureResult = 0f
                                        try {
                                            pressureResult =
                                                pressureET.text.toString().trim().toFloat()
                                            mViewModel.setPressNumber = pressureResult

                                            mViewModel.setInitCollectDelay =
                                                initDelayET.text.toString().trim().toInt()
                                            canSave = true
                                        } catch (e: Exception) {
                                            canSave = false
                                            ToastUtils.show("请输入正确格式的参数")
                                        }

                                    } else {
                                        ToastUtils.show("当前参数不能为空")
                                        canSave = false
                                    }
                                } else {
                                    if (!deviceName.text.toString().trim()
                                            .isNullOrEmpty() && !taskName.text.toString().trim()
                                            .isNullOrEmpty() && !delayTimeET.text.toString().trim()
                                            .isNullOrEmpty()
                                    ) {
                                        canSave = true
                                    } else {
                                        ToastUtils.show("当前任务名称/时间间隔 不能为空")
                                        canSave = false
                                    }
                                }

                                if (canSave) {
                                    if (HBluetooth.getInstance().isConnected) {
                                        HBluetooth.getInstance().sender()?.let { it1 ->
                                            mViewModel.clickType = 17
                                            mViewModel.setIntervalTime =
                                                delayTimeET.text.toString().trim().toInt()
                                            var cmd =
                                                "FF55AA0082" + getAddress() + "4502000010300078"

                                            var deviceBytes = get40Bytes()
                                            System.arraycopy(
                                                deviceName.text.toString()
                                                    .commonAsUtf8ToByteArray(),
                                                0,
                                                deviceBytes,
                                                0,
                                                deviceName.text.toString()
                                                    .commonAsUtf8ToByteArray().size
                                            )
                                            var taskNameBytes = get40Bytes()
                                            System.arraycopy(
                                                taskName.text.toString().commonAsUtf8ToByteArray(),
                                                0,
                                                taskNameBytes,
                                                0,
                                                taskName.text.toString()
                                                    .commonAsUtf8ToByteArray().size
                                            )
                                            var taskDescBytes = get40Bytes()
                                            if (!taskDesc.text.toString().trim().isNullOrEmpty()) {
                                                System.arraycopy(
                                                    taskDesc.text.toString()
                                                        .commonAsUtf8ToByteArray(),
                                                    0,
                                                    taskDescBytes,
                                                    0,
                                                    taskDesc.text.toString()
                                                        .commonAsUtf8ToByteArray().size
                                                )
                                            }
                                            cmd =
                                                cmd + MyUtil.bytes2Hex(deviceBytes) + MyUtil.bytes2Hex(
                                                    taskNameBytes
                                                ) + MyUtil.bytes2Hex(taskDescBytes)
                                            mViewModel.sendCommonCMD(
                                                it1,
                                                cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                                            )
                                        }
                                    } else {
                                        ToastUtils.show("请先连接设备后再操作")
                                    }
                                }

                            }
                            btnPopupWindow.setOnClickListener {
                                dismiss()
                            }
                            linearLayout.setOnClickListener {}
                            showAtLocation(contentView, Gravity.CENTER, 0, 0)
                        }
                    }
                }
            }
        })
        mViewModel.tasklistData.observe(this, Observer {
            Log.e("tasklistData", "tasklistData " + it.toString())
            if (it.size > 0) {
                mBind.noDataIv.visibility = View.GONE
            } else {
                mBind.noDataIv.visibility = View.VISIBLE
            }
            mTaskAdapter.setNewInstance(it)
            mTaskAdapter.notifyDataSetChanged()
            mBind.chooseStartTime.text = mmkv.getString(ValueKey.COLLECTION_START_TIME, "")
            mBind.chooseEndTime.text = mmkv.getString(ValueKey.COLLECTION_END_TIME, "")
        })

        LiveDataEvent.connectSPPDevice.observe(this, Observer {
            if (LiveDataEvent.connectSPPDevice.value?.connect == true) {

                lifecycleScope.launch {
                    Log.e("对话框", "对话框")
                    delay(500)
                    dialog = WaitDialog.show("请等待")
                    dialog.onBackPressedListener = OnBackPressedListener {
                        dialog.doDismiss()
                        false
                    }
                    connectDevice(LiveDataEvent.connectSPPDevice.value!!.bluetoothDevice as BluetoothDevice)
                }

            }
        })
        LiveDataEvent.showTitle.observe(this, Observer {
            if (it) {
                lifecycleScope.launch {
                    mBind.titleTv.visibility = View.VISIBLE
                    Log.e(
                        "查询成功", "更新的标题 " + mmkv.getString(
                            ValueKey.CURRENT_DEVICE_NAME, ""
                        ).toString()
                    )
                    mBind.titleTv.text = "当前设备：" + mmkv.getString(
                        ValueKey.CURRENT_DEVICE_NAME, ""
                    ).toString()
                }

            }
        })


        LiveDataEvent.currentMode.observe(this, Observer {

            lifecycleScope.launch {

                when (it) {
                    //0:空闲模式 1：离线模式 3：在线模式
                    0 -> {
                        mBind.modeTipsTv.visibility = View.VISIBLE
                        mBind.modeTipsTv.text = "待机模式"
                    }

                    1 -> {
                        mBind.modeTipsTv.visibility = View.VISIBLE
                        mBind.modeTipsTv.text = "定时采集模式"
                    }

                    2 -> {
                        mBind.modeTipsTv.visibility = View.VISIBLE
                        mBind.modeTipsTv.text = "压力触发模式"
                    }

                    3 -> {
                        mBind.modeTipsTv.visibility = View.VISIBLE
                        mBind.modeTipsTv.text = "测试模式"
                    }
                }

            }

        })
    }

    override fun onResume() {
        super.onResume()
        Log.e("onResume", "任务")
        initListener()
        immersionBar {
            titleBar(mBind.customToolbar)
        }
        mViewModel.checkNeedRereadSystemInfo()
    }


    fun setNewMode() {
        lifecycleScope.launch {
            if (HBluetooth.getInstance().isConnected) {
                HBluetooth.getInstance().sender()?.let { it1 ->
                    mViewModel.clickType = 20
                    var cmd = "FF55AA000A" + getAddress() + "45010000000000C8"
                    mViewModel.sendCommonCMD(
                        it1, cmd + CRC16Utils.checkCRC(MyUtil.hex2Bytes(cmd))
                    )
                }
            } else {
                ToastUtils.show("请先连接设备后再操作")
            }
        }
    }

    fun setConnectStatusRightImage() {
        if (HBluetooth.getInstance().isConnected) {
            Log.e("右上角", " 已经连接")
            mBind.customToolbar.setRightDrawable(com.channel.temperature.collect.R.mipmap.icon_connected)
        } else {
            Log.e("右上角", " 没有连接")
            mBind.customToolbar.setRightDrawable(com.channel.temperature.collect.R.mipmap.icon_unconnected)
        }
    }

//    override fun onConfigurationChanged(newConfig: Configuration) {
//        super.onConfigurationChanged(newConfig)
//        Log.e("TaskFragment", "TaskFragment 111111111111111111")
//        AutoSizeConfig.getInstance()
//            .setScreenWidth(ScreenUtils.getScreenSize(requireActivity())[0]);
//        AutoSizeConfig.getInstance()
//            .setScreenHeight(ScreenUtils.getScreenSize(requireActivity())[1]);
//        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            AutoSize.autoConvertDensityBaseOnHeight(requireActivity(), 640f);
//        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            AutoSize.autoConvertDensityOfGlobal(requireActivity());
//        }
//    }

}